package com.taxshare.purchaser.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.constant.ResultConstant;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.mapper.*;
import com.taxshare.purchaser.view.dto.InvoiceBatchOperationDTO;
import com.taxshare.purchaser.view.dto.InvoiceBatchOperationMainDTO;
import com.taxshare.response.beans.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @ClassName: InvoiceBatchOperationService
 * @Description:
 * @author: zy
 * @date: 2021/5/24
 */
@Slf4j
@Service
@Transactional
public class InvoiceBatchOperationService extends ServiceImpl<InvoicePoolMapper, InvoicePoolEntity> {

    @Autowired
    InvoiceBatchOperationMapper invoiceBatchOperationMapper;

    @Autowired
    InvoiceCollectionMapper invoiceCollectionMapper;

    @Autowired
    TrainTicketMapper trainTicketMapper;

    @Autowired
    TaxiTicketMapper taxiTicketMapper;

    @Autowired
    PlaneTicketMapper planeTicketMapper;

    @Autowired
    QuotaTicketMapper quotaTicketMapper;

    @Autowired
    TollTicketMapper tollTicketMapper;

    @Autowired
    BusTicketMapper busTicketMapper;

    @Autowired
    MachinTicketMapper machinTicketMapper;

    @Autowired
    InvoicePoolMapper invoicePoolMapper;

    @Autowired
    TrainTicketPoolMapper trainTicketPoolMapper;

    @Autowired
    BusTicketPoolMapper busTicketPoolMapper;

    @Autowired
    MachinTicketPoolMapper machinTicketPoolMapper;

    @Autowired
    TaxiTicketPoolMapper taxiTicketPoolMapper;

    @Autowired
    TollTicketPoolMapper tollTicketPoolMapper;

    @Autowired
    QuotaTicketPoolMapper quotaTicketPoolMapper;

    @Autowired
    PlaneTicketPoolMapper planeTicketPoolMapper;

    @Autowired
    PlaneTicketDetailMapper planeTicketDetailMapper;
    /**
     * 发票删除（批量）接口（根据发票代码和号码或者单据号删除、删发票池）
     *
     * @return
     */
    public Response deleteInvoiceCode(InvoiceBatchOperationMainDTO invoiceBatchOperationMainDTO) {
        List<InvoiceBatchOperationDTO> invoiceBatchOperationDTOList = invoiceBatchOperationMainDTO.getData();
        for (int i = 0; i < invoiceBatchOperationDTOList.size(); i++) {
            InvoiceBatchOperationDTO invoiceBatchOperationDTO = invoiceBatchOperationDTOList.get(i);
            //发票代码、发票号码和发票类型 判空
            if (StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceNo()) || StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceCode()) || StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceType())) {
                return Response.error(ResultConstant.RET_P0013_CODE, ResultConstant.RET_P0013_MSG);
            }

            String invoiceCode = invoiceBatchOperationDTO.getInvoiceCode();
            String invoiceNo = invoiceBatchOperationDTO.getInvoiceNo();
            String invoiceType = invoiceBatchOperationDTO.getInvoiceType();
            if (CodeConstant.OCRINVOICE_LIST.contains(invoiceType)) {
                //查询
                QueryWrapper<InvoicePoolEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("invoice_code", invoiceCode);
                wrapper.eq("invoice_no", invoiceNo);
                //删除增值税发票数据
                invoicePoolMapper.delete(wrapper);
//                //查询
//                QueryWrapper<InvoicePoolEntity> poolWrapper = new QueryWrapper<>();
//                poolWrapper.eq("invoice_code", invoiceCode);
//                poolWrapper.eq("invoice_no", invoiceNo);
//                invoicePoolMapper.delete(poolWrapper);
            } else {
                //处理非增值税发票数据
                if (CodeConstant.INVOICETYPE_HCP.equals(invoiceType)) {
                    //火车票【10503】
                    QueryWrapper<TrainTicketPoolEntity> wrapper = new QueryWrapper<>();

//                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<TrainTicketPoolEntity> integer = trainTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<TrainTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    trainTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_CZP.equals(invoiceType)) {
                    //出租车发票【10500】
                    QueryWrapper<TaxiTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<TaxiTicketPoolEntity> integer = taxiTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<TaxiTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    taxiTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_DEFP.equals(invoiceType)) {
                    //定额发票【10200】
                    QueryWrapper<QuotaTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<QuotaTicketPoolEntity> integer = quotaTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<QuotaTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    quotaTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_FJP.equals(invoiceType)) {
                    //航空运输电子客票行程单【10506】
                    QueryWrapper<PlaneTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("user_name", invoiceCode);
                    wrapper.eq("ticket_no", invoiceNo);
                    List<PlaneTicketPoolEntity> integer = planeTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<PlaneTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    planeTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_GLFP.equals(invoiceType)) {
                    //过路费发票【10507】
                    QueryWrapper<TollTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<TollTicketPoolEntity> integer = tollTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<TollTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    tollTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_JDFP.equals(invoiceType)) {
                    //机打发票【10400】
                    QueryWrapper<MachinTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<MachinTicketPoolEntity> integer = machinTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<MachinTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    machinTicketPoolMapper.delete(wrapperDel);
                } else if (CodeConstant.INVOICETYPE_QCP.equals(invoiceType)) {
                    //客运汽车【10505】
                    QueryWrapper<BusTicketPoolEntity> wrapper = new QueryWrapper<>();

                    wrapper.eq("invoice_code", invoiceCode);
                    wrapper.eq("invoice_no", invoiceNo);
                    List<BusTicketPoolEntity> integer = busTicketPoolMapper.selectList(wrapper);
                    if (integer.isEmpty()) {
                        return Response.error(CodeConstant.ERROR,"invoiceNo:" + invoiceNo + " " + "invoiceCode:" + invoiceCode + " " + "该发票不存在，请检查！");
                    }
                    //删除增值税发票数据
                    QueryWrapper<BusTicketPoolEntity> wrapperDel = new QueryWrapper<>();
                    wrapperDel.in("uuid", integer.get(0).getUuid());
                    busTicketPoolMapper.delete(wrapperDel);
                }
            }
        }

        return Response.success();
    }

    /**
     * 发票删除（批量）接口（根据发票单据号删除、删发票池）
     *
     * @return
     */
    public Response deleteDocno(List<String> docnolist) {
        //发票单据号 判空
        if (docnolist != null || docnolist.size() > 0) {
            for (int i = 0; i < docnolist.size(); i++) {
                //查询
                QueryWrapper<InvoiceBatchOperationEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("invoice_code", docnolist.indexOf(i));

                List<InvoiceBatchOperationEntity> integer = invoiceBatchOperationMapper.selectList(wrapper);
                if (integer.isEmpty()) {
                    int docNo = docnolist.indexOf(i);
                    return Response.error("docNo:" + docNo + " " + "PUR_113");
                }
            }

            //删除
            QueryWrapper<InvoiceBatchOperationEntity> Wrapper = new QueryWrapper();
            Wrapper.in("doc_no", docnolist);
            this.removeInvoice(Wrapper);
            return Response.success();
        } else {
            return Response.error(ResultConstant.RET_P0015_CODE, ResultConstant.RET_P0015_MSG);
        }
    }

    /**
     * 发票（批量）更新审批状态和单据号接口（根据发票代码和号码）
     *
     * @return
     */
    public Response updateDocno(List<InvoiceBatchOperationDTO> invoiceBatchOperationDTOList) {
        for (int i = 0; i < invoiceBatchOperationDTOList.size(); i++) {
            InvoiceBatchOperationDTO invoiceBatchOperationDTO = invoiceBatchOperationDTOList.get(i);
            //发票号码和发票代码 判空
            if (StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceNo()) || StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceCode())) {
                return Response.error(ResultConstant.RET_P0013_CODE, ResultConstant.RET_P0013_MSG);
            }
            //单据号和单据状态 判空
            if (StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceCode()) || StrUtil.hasBlank(invoiceBatchOperationDTO.getDocState())) {
                return Response.error(ResultConstant.RET_P0014_CODE, ResultConstant.RET_P0014_MSG);
            }
            //更新 审批状态和单据号
            UpdateWrapper<InvoicePoolEntity> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("invoice_code", invoiceBatchOperationDTO.getInvoiceCode())
                    .eq("invoice_no", invoiceBatchOperationDTO.getInvoiceNo())
                    .set("doc_no", invoiceBatchOperationDTO.getDocNo())
                    .set("doc_state", invoiceBatchOperationDTO.getDocState());
            InvoicePoolEntity invoicePoolEntity = new InvoicePoolEntity();
            int result = baseMapper.update(invoicePoolEntity, updateWrapper);
            if (result != 1) {
                return Response.error(ResultConstant.RET_D0002_CODE, ResultConstant.RET_D0002_MSG);
            }
            return Response.success();
        }
        return Response.success();
    }

    /**
     * 发票（批量）更新报销状态（根据发票代码和号码）
     *
     * @return
     */
    public Response updateReimbursementStatus(InvoiceBatchOperationMainDTO invoiceBatchOperationMainDTO) {
        List<InvoiceBatchOperationDTO> invoiceBatchOperationDTOList = invoiceBatchOperationMainDTO.getData();
        if (CollUtil.isEmpty(invoiceBatchOperationDTOList)){
            return Response.error(ResultConstant.RET_P0017_CODE,ResultConstant.RET_P0017_MSG);
        }
        for (int i = 0; i < invoiceBatchOperationDTOList.size(); i++) {
            InvoiceBatchOperationDTO invoiceBatchOperationDTO = invoiceBatchOperationDTOList.get(i);
            //发票号码和发票代码 判空
            if (StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceNo()) || StrUtil.hasBlank(invoiceBatchOperationDTO.getInvoiceCode())) {
                return Response.error(ResultConstant.RET_P0013_CODE, ResultConstant.RET_P0013_MSG);
            }
            QueryWrapper<InvoicePoolEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("invoice_code",invoiceBatchOperationDTO.getInvoiceCode());
            queryWrapper.eq("invoice_no",invoiceBatchOperationDTO.getInvoiceNo());
            queryWrapper.eq("reimbursement_status",CodeConstant.COMM_CODE_2);
            if (invoicePoolMapper.selectCount(queryWrapper)>0) {
                return Response.error(CodeConstant.T0001,"该发票已报销，不可更改报销状态，请检查！");
            }
            //单据号和单据状态 判空
            if (StrUtil.hasBlank(invoiceBatchOperationDTO.getReimbursementStatus())) {
                return Response.error(ResultConstant.RET_P0016_CODE, ResultConstant.RET_P0016_MSG);
            }
            UpdateWrapper<InvoicePoolEntity> updateWrapper = new UpdateWrapper();
            updateWrapper.eq("invoice_code", invoiceBatchOperationDTO.getInvoiceCode())
                    .eq("invoice_no", invoiceBatchOperationDTO.getInvoiceNo())
                    .set("reimbursement_status", invoiceBatchOperationDTO.getReimbursementStatus());
            InvoicePoolEntity invoicePoolEntity = new InvoicePoolEntity();
            int result = baseMapper.update(invoicePoolEntity, updateWrapper);
            if (result != 1) {
                return Response.error(ResultConstant.RET_D0002_CODE, ResultConstant.RET_D0002_MSG);
            }
            return Response.success();
        }
        return Response.success();
    }

    private <T> void removeInvoice(QueryWrapper<T> wrapper) {
    }

}